<template>
  <div class="login">
    <van-nav-bar title="会员登录" left-arrow @click-left="$router.go(-1)"/>
    <div class="container">
      <div class="title">
        <h3>手机号登录</h3>
        <p>未注册的手机号登录后将自动注册</p>
      </div>

      <div class="from">
        <div class="from-item">
          <input v-model="smsCode.mobile" @input="handleInput()" type="text" class="inp" placeholder="请输入手机号码"/>
        </div>
        <div class="from-item">
          <input v-model="smsCode.captchaCode" @input="handleInput()" type="text" class="inp"
                 placeholder="请输入图形验证码"/>
          <img class="captcha" :src="captcha.base64" alt="" @click="getPicCode()"/>
        </div>
        <div class="from-item">
          <input type="text" @input="handleLoginInput()" v-model="loginUser.smsCode" class="inp"
                 placeholder="请输入短信验证码"/>
          <button ref="smsBtn" :class="{ 'sms-btn': true, 'btn-gray': isGray }" @click="sendSmsCode()" disabled>
            {{ interval.second === interval.totalSecond ? '获取验证码' : interval.second + '秒后重新发送' }}
          </button>
        </div>
      </div>
      <div class="login-btn" @click="getToken">
        <button ref="loginBtn" :class="{ 'btn-gray': btnGray }" disabled>登录</button>
      </div>
    </div>
  </div>
</template>

<script>
import { getPicCode, sendSms, login } from '@/api/login'
import { mapActions } from 'vuex'

export default {
  data () {
    return {
      isGray: true,
      btnGray: true,
      interval: {
        timeId: null,
        second: 60,
        totalSecond: 60
      },
      captcha: {},
      loginUser: {
        smsCode: ''
      },
      smsCode: {
        captchaCode: '',
        captchaKey: '',
        mobile: ''
      }
    }
  },
  computed: {},
  methods: {
    ...mapActions('user', ['setToken']),
    async getPicCode () {
      this.captcha = await getPicCode()
      this.smsCode.captchaKey = this.captcha.key
    },
    async sendSmsCode () {
      if (!this.validFn()) {
        return
      }
      if (this.interval.timeId || this.interval.second !== this.interval.totalSecond) {
        this.$toast('倒计时未结束，请一分钟后再试')
        return
      }
      // 发短信验证码
      const params = JSON.parse(JSON.stringify(this.smsCode))
      try {
        await sendSms(params)
      } catch (err) {
        this.$toast(err ?? err.message)
        return
      }
      this.$refs.smsBtn.disabled = true
      this.isGray = true
      this.$toast('发送成功，请注意查收')
      // 开始倒计时
      this.interval.timeId = setInterval(() => {
        this.interval.second -= 1
        if (this.interval.second <= 0) {
          this.$refs.smsBtn.disabled = false
          this.isGray = false
          clearInterval(this.interval.timeId)
          this.interval.timeId = null
          this.interval.second = this.interval.totalSecond
          this.getPicCode()
        }
      }, 1000)
    },
    async getToken () {
      const params = JSON.parse(JSON.stringify(this.loginUser))
      params.mobile = this.smsCode.mobile
      const tokenInfo = await login(params)
      await this.setToken({
        userId: tokenInfo.userId,
        token: tokenInfo.token
      })
      await this.$router.push('/')
      this.$toast('登录成功')
    },
    handleInput (event) {
      const {
        mobile,
        captchaCode
      } = this.smsCode
      if (mobile && captchaCode) {
        this.$refs.smsBtn.disabled = false
        this.isGray = false
      }
    },
    handleLoginInput (event) {
      const { smsCode } = this.loginUser
      if (smsCode) {
        this.$refs.loginBtn.disabled = false
        this.btnGray = false
      }
    },
    validFn () {
      if (!(/^1\d{10}$/.test(this.smsCode.mobile))) {
        this.$toast('请输入正确手机号')
        return false
      }
      if (!(/^[A-Za-z0-9]{4}$/i.test(this.smsCode.mobile))) {
        this.$toast('请输入正确验证码')
        return false
      }
      return true
    }
  },
  mounted () {
    // 获取图片验证码
    this.getPicCode()
  },
  destroyed () {
    if (!this.interval.timeId) {
      clearInterval(this.interval.timeId)
    }
  }
}
</script>

<style lang="less" scoped>
::v-deep .van-nav-bar__title {
  font-weight: 400;
}

.container {
  margin: 10px 25px;

  .btn-gray:disabled {
    background: #ccc;
    /* 自己想用的灰 */
    border-color: #bbb;
    color: #666 !important;
    cursor: not-allowed;
    /* 鼠标变成禁止符号 */
    opacity: 0.7;
    /* 想再“灰”一点可降透明度 */
  }

  .title {
    margin-top: 80px;

    h3 {
      font-size: 27px;
      font-weight: 400;
    }

    p {
      height: 40px;
      color: #b3b3b3;
      font-size: 14px;
      line-height: 40px;
    }
  }

  .from {
    display: flex;
    flex-direction: column;
    justify-content: left;

    .from-item {
      height: 48px;
      border-bottom: solid 1px rgb(246, 244, 245);
      display: flex;
      align-items: center;
      justify-content: center;
      margin-bottom: 15px;

      .inp {
        font-size: 14px;
        height: 29px;
        width: 100%;
        text-align: left;
        flex: 2;
      }

      .inp::placeholder {
        color: #b3b3b3;
      }

      .captcha {
        height: 28px;
        flex: 1;

      }

      .sms-btn {
        width: 150px;
        flex: 1;
        font-size: 14px;
        color: #cea26a;
        border: none;
        background: transparent;
        /* 背景完全透明 = 无色 */
      }

    }
  }

  .login-btn {
    button {
      margin-top: 30px;
      display: inline-block;
      height: 40px;
      width: 100%;
      border-radius: 20px;
      border: none;
      background-image: linear-gradient(to right,
      rgb(237, 180, 59) 0%,
      rgb(255, 147, 18) 100%);

    }

  }
}
</style>
